#coding=utf-8
from uliweb import expose
from uliweb import expose, decorators

def __begin__():
    from uliweb import functions
    return functions.require_login()

def boolean_convert(b, obj):
    if b:
        return '是'
    else:
        return '否'

@expose('/riskpoint/points')
class RiskPointView(object):
    def __init__(self):
        from uliweb.orm import get_model

        self.model = get_model('riskpoint')
        
    def _create_query(self, url):
        """
        创建查询View
        """
        from uliweb.orm import get_model
        from uliweb.utils.generic import QueryView
        from uliweb.form import UnicodeField, SelectField, StringField, DateField
        from plugs.ui.jquery.jqcombobox.widgets import JQComboBoxField
        from plugs.ui.jquery.uimultiselect.widgets import UIMultiSelectField
        from query.forms import QueryForm
        from uliweb.utils.generic import ReferenceSelectField
        from plugs.ui.jquery.jquery.widgets import DatePicker

        
        begin_date = DateField('开始日期', build=DatePicker)
        end_date = DateField('结束日期', build=DatePicker)
        
        check_depart = ReferenceSelectField('kfzx', label='检查单位')
        point_id = UnicodeField(label='风险点序号')
        risk_desc = UnicodeField(label='风险点描述')
        risk_sys = UnicodeField(label='系统名称')
        status = UnicodeField(label='风险点状态')
        fields = [('check_depart', check_depart),('risk_sys', risk_sys),
                  ('point_id', point_id), ('risk_desc',risk_desc), 
                  ('status',status),('begin_date',begin_date),
                  ('end_date',end_date)]
        layout = [('check_depart','point_id'),('risk_sys','risk_desc'),('status','begin_date','end_date')]
        query = QueryView(self.model, ok_url=url, fields=fields, layout=layout, form_cls=QueryForm)
        return query
    
    @expose('')
    def list(self):
        """
        风险点列表
        """
        
        from uliweb.utils.generic import ListView, get_sort_field
        from uliweb.orm import get_model
        from uliweb.core.html import Tag
        from uliweb import request
        from sqlalchemy.sql import select,and_
        from uliweb import orm
        System = get_model('system')
        Task_dev = get_model('tasks_develop')
        
        type = request.GET.get('type', 'list')
        query = self._create_query(url_for(self.__class__.list))
        c = query.run()
        
        pageno = int(request.values.get('page', 1)) - 1
        rows_per_page=int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))

            
        condition = None
        #process request.POST
        if request.user.department == '2' and request.user.is_gm:
            condition = (self.model.c.check_depart==request.user._kfzx_) & condition
        
#        if c.get('tx'):
#            condition = (self.model.c.lead_tx.like('%'+c['tx']+'%')) & condition
        if c.get('check_depart'):
            condition = (self.model.c.check_depart==c['check_depart']) & condition
        if c.get('point_id'):
            condition = (self.model.c.point_id.like('%'+c['point_id']+'%')) & condition
        if c.get('risk_desc'):
            condition = (self.model.c.risk_desc.like('%'+c['risk_desc']+'%')) & condition
        if c.get('risk_sys'):
            condition = (self.model.c.system.in_(select([System.c.id],and_(System.c.abbr.like('%'+c['risk_sys']+'%')))) | self.model.c.risk_sys.like('%'+c['risk_sys']+'%') | self.model.c.sub_sys.like('%'+c['risk_sys']+'%')) & condition
        if c.get('status'):
            condition = (self.model.c.status.like('%'+c['status']+'%')) & condition
        if c.get('begin_date'):
            condition = (self.model.c.modified_date>=c['begin_date']) & condition
        if c.get('end_date'):
            condition = (self.model.c.modified_date<=c['end_date']) & condition
        
        order_by = get_sort_field(self.model) or []
        
        
        def point_id(value, obj):
            return str(Tag('a', obj.point_id, href="/riskpoint/%d/view" % obj.id))
        
        fields_convert_map = {'point_id':point_id}
        view = ListView(self.model, condition=condition, fields_convert_map=fields_convert_map, 
            order_by=order_by, rows_per_page=rows_per_page, pageno=pageno)
        view.types_convert_map = {orm.BooleanProperty:boolean_convert}
        if 'data' in request.values:
            return json(view.json())
        elif 'download' in request.values:
#            def system(value, obj):
#                if obj.system:
#                    return obj.system.abbr
#                else:
#                    return value
#            fields_convert_map = {'system':system,'task_stage':task_stage}
            return view.download('riskpoint_list.xls', action='download', timeout=0)
        else:
            result = view.run(head=True, body=False)
            result.update({'query_form':query.form, 'table':view})
            return result
    @expose('/riskpoint/<int:id>/view')    
    def view(self, id):
        """
        问题显示
        """
        
        from uliweb.utils.generic import DetailView
        from uliweb import orm
#        from forms import RiskpointForm
#        from uliweb.form.layout import TableLayout
#        
#        RiskpointForm.layout_class = TableLayout
        
        obj = self.model.get(int(id))
        layout = [
                '-- 风险点信息 --',
                ('point_id','review'),
                ('check_depart','risk_sys','check_num'),
                ('policy'),
                ('target'),
                ('status','busi_supervisor'),
                ('level','in_project','has_emergency'),
                ('has_monitor','has_drilled','has_tech'),
                ('has_busi_solution','has_busi_emergency','has_auto_alarm'),
                ('risk_desc'),
                ('risk_analysis'),
                ('tech_control_desc'),
                ('busi_control_desc'),
                ('memo'),
                '-- 扩展信息 --',
                ('requirement','system','sub_sys'),
                ('modified_date','modified_user'),
                ]
        
        view = DetailView(self.model, obj=obj, layout=layout)
        view.types_convert_map = {orm.BooleanProperty:boolean_convert}
        return view.run()

    @expose('/riskpoint/<int:id>/edit')    
    def riskpoint_edit(self,id):
        """
        编辑风险点
        """
        
        from uliweb.utils.generic import EditView
        from uliweb.orm import get_model
        from uliweb import request, redirect
        from forms import RiskpointForm
        from uliweb.form.layout import TableLayout
        
        RiskpointForm.layout_class = TableLayout
#        def post_created_form(fcls, model,obj):
#            fcls.layout_class = TableLayout
#            fcls.task_id.required=True
#            sys = task_dev.get(task_dev.c.task_id == fcls.task_id)
#            if not sys:
#                error['task_id'] = '任务编号填写有误或未填写！'
            
        System = get_model('system')
        Kfzx = get_model('kfzx')
        task_dev = get_model('tasks_develop')
#        Riskpoint = get_model('riskpoint')
        
        obj = self.model.get(int(id))
    #       if obj._task_:
    #           meta = 'EditForm'
    #       else:
    #           meta = 'EditReqForm'
            
#        def pre_save(obj, data):
#            data['modified_user'] = request.user.id
#            
#            data['system'] = None
#            if data['solution_mode'] == '1' and data['task_id']:
#                task_flag = task_dev.get(task_dev.c.id == data['task_id'])
#                if task_flag:
#                    data['system'] = task_flag._task_sys_
#    #                  return redirect(url_for(tests_test_list))
#                else:
#                    data['task_id'] = None
#            if data['solution_mode'] == '1':
#               data['nondev_riskpoint_status'] = None
            
        def post_created_form(fcls, model, obj):
            from uliweb.form import Submit
            if request.user.is_superuser:
                fcls.form_buttons = [Submit(value=_('Save'), _class="button"), 
                    '<a href="/riskpoint/delete/%s">删除</a>' % id]
                
        fields = ['point_id','review','in_project','check_depart','risk_sys',
                'check_num','level','status','policy','target',
                'has_monitor','has_emergency','has_drilled','has_tech',
                'busi_supervisor','has_busi_solution','has_busi_emergency',
                'has_auto_alarm','risk_desc','risk_analysis','tech_control_desc',
                'busi_control_desc','memo','system','sub_sys','requirement',
                'modified_date','modified_user']
        if request.user.is_superuser:
            static_fields = ['point_id','modified_date','modified_user']
        elif has_role(request.user,'riskpoint_manager'):
            static_fields = ['point_id',
#                'review',
#                'in_project',
#                'check_depart',
#                'risk_sys',
#                'check_num',
#                'level',
#                'policy',
#                'target',
#                'has_monitor','has_emergency','has_drilled','has_tech',
#                'busi_supervisor','has_busi_solution','has_busi_emergency',
#                'has_auto_alarm',
#                'risk_desc',
#                'risk_analysis',
#                'tech_control_desc',
#                'busi_control_desc',
#                'memo',
                'system','sub_sys',
#                'requirement',
                'modified_date','modified_user']
        else:
            static_fields = ['point_id','review','in_project','check_depart','risk_sys',
                'check_num','level',
#                'status',
                'policy','target',
                'has_monitor','has_emergency','has_drilled','has_tech',
                'busi_supervisor','has_busi_solution','has_busi_emergency',
                'has_auto_alarm','risk_desc','risk_analysis',
#                'tech_control_desc',
#                'busi_control_desc',
                'memo','system','sub_sys','requirement',
                'modified_date','modified_user']

    
        if request.user.is_superuser:
            layout = [
                    '-- 风险点信息 --',
                    ('point_id','review'),
                    ('check_depart','risk_sys','check_num'),
                    ('policy'),
                    ('target'),
                    ('status','busi_supervisor'),
                    ('level','in_project','has_emergency'),
                    ('has_monitor','has_drilled','has_tech'),
                    ('has_busi_solution','has_busi_emergency','has_auto_alarm'),
                    ('risk_desc'),
                    ('risk_analysis'),
                    ('tech_control_desc'),
                    ('busi_control_desc'),
                    ('memo'),
                    '-- 扩展信息 --',
                    ('requirement'),
                    ('system','sub_sys'),
                    ('modified_date','modified_user'),
                    ]
        else:
            layout = [
                    '-- 风险点信息 --',
                    ('point_id','review','in_project'),
                    ('check_depart','risk_sys','check_num','level'),
                    ('policy'),
                    ('target'),
                    ('status','busi_supervisor'),
                    ('has_monitor','has_emergency','has_drilled','has_tech'),
                    ('has_busi_solution','has_busi_emergency','has_auto_alarm'),
                    ('risk_desc'),
                    ('risk_analysis'),
                    ('tech_control_desc'),
                    ('busi_control_desc'),
                    ('memo'),
                    '-- 扩展信息 --',
                    ('requirement'),
                    ('system','sub_sys',),
                    ('modified_date','modified_user'),
                    ]

        def get_form_field(name, obj):
            from uliweb.utils.generic import RemoteField
            if request.user.is_superuser or has_role(request.user,'riskpoint_manager'):
                if name == 'requirement':
                    if obj._requirement_:
                        alt = obj.requirement.title
                    else:
                        alt = ''
#                        alt = None
#                        obj.requirement = None
                    return RemoteField('准开发需求', name=name, #required=True, 
                        url='/requirements/search', alt=alt, default=None)
#            if name == 'task_id':
#                task_flag = task_dev.get(task_dev.c.id == obj._task_id_)
#                if task_flag:
#                    alt = obj.task_id.name
#                else:
#                    alt = ''
#                return RemoteField('执行任务', name=name, 
#                    url='/tasks/search?flag=1', alt=alt, datatype=int,default=None)
            
    #       def post_created_form(fcls, model, obj):
    #           if not obj._task_:
    #               fcls.owner_sys.query = obj.requirement.systems.all()
    #           fcls.systems.query = obj.requirement.systems.all()
        
    #       view = EditView('riskpoint', '/risks', 
    #           obj=obj, post_created_form=post_created_form, meta=meta, pre_save=pre_save)
        view = EditView('riskpoint', ok_url=url_for(self.__class__.list), obj=obj,
#                    pre_save=pre_save, 
                    fields=fields,layout = layout,
                    static_fields = static_fields,get_form_field = get_form_field,
                    form_cls=RiskpointForm, 
#                    post_created_form=post_created_form
                    )
        
        return view.run()
    
    @expose('/riskpoint/add')
    @decorators.check_role('riskpoint_manager')
    def riskpoint_add(self):
        from uliweb.utils.generic import AddView
        from uliweb.orm import get_model
    #    from uliweb.form.layout import TableLayout
    #    from forms import TestForm
    #    from sqlalchemy.sql import and_, or_, not_
        from forms import RiskpointForm
        from uliweb.form.layout import TableLayout
        
        RiskpointForm.layout_class = TableLayout
        
    #    TestForm.layout_class = TableLayout
        
        def post_created_form(fcls, model):
            fcls.layout_class_args = {'label_fix':True}
#        name=None
#        obj_req=None
        def get_form_field(name):
            from uliweb.utils.generic import RemoteField
            if request.user.is_superuser or has_role(request.user,'riskpoint_manager'):
                if name == 'requirement':
                    alt = ''
                    return RemoteField('准开发需求', name=name, #required=True, 
                        url='/requirements/search', alt=alt, default=None)
        
        layout = [
                '-- 风险点信息 --',
                ('point_id','review'),
                ('check_depart','risk_sys','check_num'),
                ('policy'),
                ('target'),
                ('status','busi_supervisor'),
                ('level','in_project','has_emergency'),
                ('has_monitor','has_drilled','has_tech'),
                ('has_busi_solution','has_busi_emergency','has_auto_alarm'),
                ('risk_desc'),
                ('risk_analysis'),
                ('tech_control_desc'),
                ('busi_control_desc'),
                ('memo'),
                '-- 扩展信息 --',
                ('requirement'),
                ('system','sub_sys'),
#                ('modified_date','modified_user'),
                ]
        
    #    if request.user.department in ('2', '3'):
        view = AddView('riskpoint', url_for(self.__class__.riskpoint_add), 
#                pre_save=pre_save,
                get_form_field = get_form_field,
                layout=layout, 
                form_cls=RiskpointForm, post_created_form=post_created_form,
                )
        return view.run()
    ###    else:
    #        flash('你不是开发人员和测试人员，无法添加新测试功能点！')
    #        return redirect(url_for(tests_test_list))
    
    @expose('/riskpoint/delete/<int:id>')
    @decorators.check_role('riskpoint_manager')
    def riskpoint_delete(self, id):
        """
        删除风险点
        """
        
        from uliweb.utils.generic import DeleteView
        from uliweb.orm import get_model
#        Riskpoint = get_model('riskpoint')
        Risksolution= get_model('risksolution')
        obj = self.model.get(int(id))
        risksolution_obj = Risksolution.filter(Risksolution.c.riskpoint == obj.point_id)
        for row in risksolution_obj:
            flash('请先删除该风险点下整改措施，再删除风险点！')
            return redirect(url_for(self.__class__.view,id=id))
            
#            row.delete()

#        Risksolution.table.delete()
        view = DeleteView('riskpoint', url_for(self.__class__.list), obj=obj)
        return view.run()
    
@expose('/riskpoint/search')
def riskpoint_search():
    from uliweb.orm import get_model
    from sqlalchemy.sql import and_, or_, not_
    Riskpoint = get_model('riskpoint')
    txt = request.values.get('term')
    if not txt:
        return json([])
    
#        condition = None
    v=txt.split('_',1)
    if len(v)==1:
        txt1=v[0]
        txt2=v[0]
    else:
        txt1=v[0]
        txt2=v[1]
        
        
    result = Riskpoint.filter(and_(Riskpoint.c.point_id.like('%' + txt1 + '%') | Riskpoint.c.policy.like('%' + txt2 + '%') | Riskpoint.c.risk_desc.like('%' + txt2 + '%'))).values('id', 'point_id','risk_desc')
    search_data = []
    for x in result:
        y = {}
        y['id'] = x[1]
        y['title'] = x[1] +'_' + x[2]
#        y['title'] = x[2]
        search_data.append(y)
#    return json([{'id':x[0], 'name':(x[1]+x[2])} for x in result])
    return json(search_data)
    
@expose('/riskpoint/solutions')
class RiskSolutionView(object):
    def __init__(self):
        from uliweb.orm import get_model

        self.model = get_model('risksolution')
        
    def _create_query(self, url):
        """
        创建查询View
        """
        from uliweb.orm import get_model
        from uliweb.utils.generic import QueryView
        from uliweb.form import UnicodeField, SelectField, StringField
        from plugs.ui.jquery.jqcombobox.widgets import JQComboBoxField
        from plugs.ui.jquery.uimultiselect.widgets import UIMultiSelectField
        from query.forms import QueryForm
        from uliweb.utils.generic import ReferenceSelectField
        
        solution_mode = SelectField('解决方式', choices=settings.get_var('PARA/SOLUTION_MODE'))
#        task_stage = SelectField('执行任务状态', choices=settings.get_var('PARA/RISK_STATUS'))
        nondev_riskpoint_status = SelectField('解决状态', choices=settings.get_var('PARA/NONDEV_RISKPOINT_STATUS'))
        tech_lead_depart = ReferenceSelectField('kfzx', label='技术部门主责方')
        lead_depart = ReferenceSelectField('kfzx', label='牵头方')
        tech_co_depart = UnicodeField(label='技术部门协同方')
        task_id = UnicodeField(label='执行任务')
        solution_id = UnicodeField(label='整改事项序号')
        only_mine = SelectField('只显示我中心整改措施', choices=settings.get_var('PARA/ONLY_MINE'), default='1')
        fields = [('tech_lead_depart', tech_lead_depart),
                  ('lead_depart', lead_depart),
                  ('tech_co_depart',tech_co_depart),
                  ('solution_mode',solution_mode),
#                  ('task_stage',task_stage),
                  ('nondev_riskpoint_status',nondev_riskpoint_status),
                  ('solution_id',solution_id),
                  ('task_id',task_id),
                  ('riskpoint')]
        
        layout = [('tech_lead_depart','solution_id'),('tech_co_depart','lead_depart','solution_mode'),('nondev_riskpoint_status','task_id')]
        if request.user.department in ('2', '3'):
            fields = [('only_mine', only_mine)] + fields
            layout = [('only_mine','solution_id','tech_lead_depart'),('tech_co_depart','lead_depart','solution_mode'),('nondev_riskpoint_status','task_id')]
            
        
        query = QueryView(self.model, ok_url=url, fields=fields, layout=layout, form_cls=QueryForm)
        return query
    
    @expose('')
    def list(self):
        """
        风险点列表
        """
        
        from uliweb.utils.generic import ListView, get_sort_field
        from uliweb.orm import get_model
        from uliweb.core.html import Tag
        from uliweb import request
        from sqlalchemy.sql import select,and_
        from uliweb import orm
        from uliweb import settings
        from uliweb.utils.common import get_var, get_choice
        System = get_model('system')
        Task_dev = get_model('tasks_develop')
        
        type = request.GET.get('type', 'list')
        query = self._create_query(url_for(self.__class__.list))
        c = query.run()
        
        pageno = int(request.values.get('page', 1)) - 1
        rows_per_page=int(request.values.get('rows', settings.get_var('PARA/ROWS_PER_PAGE', 10)))

            
        condition = None
        #process request.POST
#        if request.user.department == '2' and request.user.is_gm:
#            condition = (self.model.c.tech_lead_depart==request.user._kfzx_) & condition
#        
        if c.get('riskpoint'):
            condition = (self.model.c.riskpoint == c['riskpoint']) & condition
        if c.get('only_mine') == '1':
            condition = (self.model.c.tech_lead_depart == request.user._kfzx_) & condition
        else:
            condition = condition
        if c.get('tech_lead_depart'):
            condition = (self.model.c.tech_lead_depart == c['tech_lead_depart']) & condition
        if c.get('lead_depart'):
            condition = (self.model.c.lead_depart == c['lead_depart']) & condition
        if c.get('tech_co_depart'):
            condition = (self.model.c.tech_co_depart.like('%'+c['tech_co_depart']+'%')) & condition
        if c.get('task_id'):
            condition = (self.model.c.task_id.in_(select([Task_dev.c.id],and_(Task_dev.c.task_id.like('%'+c['task_id']+'%'))))) & condition
        
#        if c.get('kfzx'):
#            condition = (self.model.c.kfzx==c['kfzx']) & condition
#        if c.get('check_id'):
#            condition = (self.model.c.check_id==c['check_id']) & condition
#        if c.get('sys_abbr'):
#            condition = (self.model.c.system.in_(select([System.c.id],and_(System.c.abbr.like('%'+c['sys_abbr']+'%')))) | self.model.c.risk_sys.like('%'+c['sys_abbr']+'%') | self.model.c.sub_sys.like('%'+c['sys_abbr']+'%')) & condition
#        if c.get('task_stage'):
#            if c['task_stage'] == '1':
#                condition = (self.model.c.task_id.in_(select([Task_dev.c.id],and_(Task_dev.c.stage == '00')))) & (self.model.c.solution_mode == '1') & condition
#            if c['task_stage'] == '2':
#                condition = (self.model.c.task_id.in_(select([Task_dev.c.id],and_(Task_dev.c.stage != '00',Task_dev.c.stage != 'FN')))) & (self.model.c.solution_mode == '1') & condition
#            if c['task_stage'] == 'F':
#                condition = (self.model.c.task_id.in_(select([Task_dev.c.id],and_(Task_dev.c.stage == 'FN')))) & (self.model.c.solution_mode == '1') & condition
#            if c['task_stage'] == 'N':
#                condition = (self.model.c.task_id == None) & (self.model.c.solution_mode == '1') & condition
        if c.get('solution_id'):
            condition = (self.model.c.solution_id.like('%'+c['solution_id']+'%')) & condition
        
        if c.get('nondev_riskpoint_status'):
            if c['nondev_riskpoint_status'] == '1':
                condition = (self.model.c.nondev_riskpoint_status == '1') & condition
            if c['nondev_riskpoint_status'] == '2':
                condition = (self.model.c.nondev_riskpoint_status == '2') & condition
            if c['nondev_riskpoint_status'] == 'F':
                condition = (self.model.c.nondev_riskpoint_status == 'F') & condition
            if c['nondev_riskpoint_status'] == 'N':
                condition = (self.model.c.nondev_riskpoint_status == 'N') & condition
            
        if c.get('solution_mode'):
            condition = (self.model.c.solution_mode==c['solution_mode']) & condition
        
        order_by = get_sort_field(self.model) or []
        
#        def nondev_riskpoint_status(value,obj):
#            task_stage = ''
#            task_flag = Task_dev.get(Task_dev.c.id == obj._task_id_)
#            
#            if obj.solution_mode == '1' and task_flag:
#                if task_flag.stage == '00':
#                    task_stage = u'未开始'
#                if task_flag.stage == 'FN':
#                    task_stage = u'完成'
#                if task_flag.stage != 'FN' and task_flag.stage != '00':
#                    task_stage = u'执行中'
#            elif obj.solution_mode == '1' and not task_flag:
#                task_stage = u'无关联任务'
#            else:
##                nondev_status = dict(settings.get_var('PARA/NONDEV_RISKPOINT_STATUS'))
##                return nondev_status[value]
#                return obj.get_display_value('nondev_riskpoint_status')
#            return task_stage
        def task_id(value, obj):
            task_flag = Task_dev.get(Task_dev.c.id == obj._task_id_)
            if task_flag:
                task_id = task_flag.task_id
            else:
                task_id = ''
            return task_id
            
        def solution_id(value, obj):
            return str(Tag('a', obj.solution_id, href="/risksolution/%d/view" % obj.id))
        
        def review(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/RISK_REVIEW_STATUS', []), obj.riskpoint.review)
            else:
                return ''
        def in_project(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/YESNO', []), obj.riskpoint.in_project)
            else:
                return ''
        def check_depart(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.check_depart.name
            else:
                return ''
        def risk_sys(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.risk_sys
            else:
                return ''
        def check_num(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.check_num
            else:
                return ''
        def level(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/RISK_LEVEL', []), obj.riskpoint.level)
            else:
                return ''
        def status(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/RISK_POINT_STATUS', []), obj.riskpoint.status)
            else:
                return ''
        
        def risk_policy(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.policy
            else:
                return ''
        def target(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.target
            else:
                return ''
            
        def has_monitor(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/YESNO', []), obj.riskpoint.has_monitor)
            else:
                return ''
        def has_emergency(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/YESNO', []), obj.riskpoint.has_emergency)
            else:
                return ''
        def has_drilled(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/YESNO', []), obj.riskpoint.has_drilled)
            else:
                return ''
        def has_tech(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/YESNO', []), obj.riskpoint.has_tech)
            else:
                return ''
        def busi_supervisor(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.busi_supervisor
            else:
                return ''
        def has_busi_solution(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/YESNO', []), obj.riskpoint.has_busi_solution)
            else:
                return ''
        def has_busi_emergency(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/YESNO', []), obj.riskpoint.has_busi_emergency)
            else:
                return ''
        def has_auto_alarm(value, obj):
            if obj.riskpoint:
                return get_choice(settings.get_var('PARA/YESNO', []), obj.riskpoint.has_auto_alarm)
            else:
                return ''
        def risk_desc(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.risk_desc
            else:
                return ''
        def risk_analysis(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.risk_analysis
            else:
                return ''
        def tech_control_desc(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.risk_analysis
            else:
                return ''
        def busi_control_desc(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.risk_analysis
            else:
                return ''
        def risk_memo(value, obj):
            if obj.riskpoint:
                return obj.riskpoint.memo
            else:
                return ''
        def requirement(value, obj):
            if obj.riskpoint and obj.riskpoint.requirement:
                return obj.riskpoint.requirement.req_id
            else:
                return '' 
        def system(value, obj):
            if obj.riskpoint and obj.riskpoint.system:
               return obj.riskpoint.system.abbr
            else:
               return '' 
            
        
        
        fields_convert_map = {'solution_id':solution_id,
#        'nondev_riskpoint_status':nondev_riskpoint_status,
                            'task_id':task_id,'review':review,
                            'in_project':in_project,'check_depart':check_depart,
                            'risk_sys':risk_sys,'check_num':check_num,
                            'level':level,'status':status,
                            'risk_policy':risk_policy,'target':target,
                            'has_monitor':has_monitor,'has_emergency':has_emergency,
                            'has_drilled':has_drilled,'has_tech':has_tech,
                            'busi_supervisor':busi_supervisor,'has_busi_solution':has_busi_solution,
                            'has_busi_emergency':has_busi_emergency,'has_auto_alarm':has_auto_alarm,
                            'risk_desc':risk_desc,'risk_analysis':risk_analysis,
                            'tech_control_desc':tech_control_desc,'busi_control_desc':busi_control_desc,
                            'risk_memo':risk_memo,'requirement':requirement,
                            'system':system,
                            }
        view = ListView(self.model, condition=condition, fields_convert_map=fields_convert_map, 
            order_by=order_by, rows_per_page=rows_per_page, pageno=pageno)
        view.types_convert_map = {orm.BooleanProperty:boolean_convert}
        if 'data' in request.values:
            return json(view.json())
        elif 'download' in request.values:
#            def system(value, obj):
#                if obj.system:
#                    return obj.system.abbr
#                else:
#                    return value
#            fields_convert_map = {'system':system,'task_stage':task_stage}
            return view.download('risksolution_list.xls', action='download', timeout=0)
        else:
            result = view.run(head=True, body=False)
            result.update({'query_form':query.form, 'table':view})
            return result
    @expose('/risksolution/<int:id>/view')    
    def view(self, id):
        """
        问题显示
        """
        
        from uliweb.utils.generic import DetailView
        from uliweb import orm
        from uliweb.orm import get_model
        from uliweb.core.html import Tag
        from uliweb import request
        from sqlalchemy.sql import select,and_
        from uliweb import orm
        
        System = get_model('system')
        Task_dev = get_model('tasks_develop')
                
        obj = self.model.get(int(id))
        def nondev_riskpoint_status(value,obj):
            task_stage = ''
            task_flag = Task_dev.get(Task_dev.c.id == obj._task_id_)
            
            if obj.solution_mode == '1' and task_flag:
                if task_flag.stage == '00':
                    task_stage = u'未开始'
                if task_flag.stage == 'FN':
                    task_stage = u'完成'
                if task_flag.stage != 'FN' and task_flag.stage != '00':
                    task_stage = u'执行中'
            elif obj.solution_mode == '1' and not task_flag:
                task_stage = u'无关联任务'
            else:
                return obj.get_display_value('nondev_riskpoint_status')
            return task_stage
        
        layout = [
                '-- 风险整改措施信息 --',
                ('riskpoint','solution_id','type'),
                ('policy','urgency'),
                ('plan_finish_date','finish_date'),
                ('zx_ammount','gs_ammount'),
                ('lead_depart','tech_lead_depart','tech_co_depart'),
                ('busi_lead_depart','busi_co_depart','yw_ammount'),
                ('solution'),
                ('solution_additional_explan'),
                ('result'),
                ('solution_mode','nondev_riskpoint_status','task_id','itsm_num'),
                ('memo'),
                ('modified_date','modified_user'),
                ]
        fields_convert_map = {'nondev_riskpoint_status':nondev_riskpoint_status}
        view = DetailView(self.model, obj=obj, fields_convert_map=fields_convert_map, layout=layout)
        view.types_convert_map = {orm.BooleanProperty:boolean_convert}
        return view.run()

    @expose('/risksolution/<int:id>/edit')    
    def risksolution_edit(self,id):
        """
        编辑风险点
        """
        
        from uliweb.utils.generic import EditView
        from uliweb.orm import get_model,do_, NotFound
        from uliweb import request, redirect
        from forms import RisksolutionForm
        from uliweb.form.layout import TableLayout
        
        RisksolutionForm.layout_class = TableLayout
#        def post_created_form(fcls, model,obj):
#            fcls.layout_class = TableLayout
#            fcls.task_id.required=True
#            sys = task_dev.get(task_dev.c.task_id == fcls.task_id)
#            if not sys:
#                error['task_id'] = '任务编号填写有误或未填写！'
            
        System = get_model('system')
        Kfzx = get_model('kfzx')
        task_dev = get_model('tasks_develop')
        Riskpoint = get_model('riskpoint')
        
        obj = self.model.get(int(id))
    #       if obj._task_:
    #           meta = 'EditForm'
    #       else:
    #           meta = 'EditReqForm'
    
        def pre_save(obj, data):
#            data['modified_user'] = request.user.id
#            print 'xxxxxxxxxxxxxxxxx', data
            riskpoint_obj = Riskpoint.get(Riskpoint.c.id == obj._riskpoint_)
            task_obj = None
            if data['task_id']:
                task_obj = task_dev.get(task_dev.c.id == data['task_id'])
            if riskpoint_obj and task_obj and riskpoint_obj.system != task_obj._task_sys_:
                do_(Riskpoint.table.update(Riskpoint.c.id==obj._riskpoint_).values(system = task_obj._task_sys_,sub_sys = task_obj.sub_sys))
#            print '---------',data
            
        def post_created_form(fcls, model, obj):
            from uliweb.form import Submit
            if request.user.is_superuser:
                fcls.form_buttons = [Submit(value=_('Save'), _class="button"), 
                    '<a href="/riskpoint/delete/%s">删除</a>' % id]
                
        fields = ['riskpoint','solution_id','type',
                    'policy','urgency',
                    'plan_finish_date','finish_date',
                    'zx_ammount','gs_ammount',
                    'lead_depart','tech_lead_depart','tech_co_depart',
                    'busi_lead_depart','busi_co_depart','yw_ammount',
                    'solution',
                    'result',
                    'solution_additional_explan',
                    'solution_mode','nondev_riskpoint_status','task_id',
                    'itsm_num',
                    'memo',
                    'modified_date','modified_user',
                    ]
        if request.user.is_superuser:
            static_fields = ['modified_date','modified_user']
        elif has_role(request.user,'riskpoint_manager'):
            static_fields = [
                    'riskpoint',
                    'solution_id','type',
#                    'policy',
#                    'urgency',
#                    'policy',
#                    'plan_finish_date',
#                    'finish_date',
                    'zx_ammount','gs_ammount',
#                    'lead_depart',
#                    'tech_lead_depart',
#                    'tech_co_depart',
                    'busi_lead_depart','busi_co_depart',
                    'yw_ammount',
                    'solution',
#                    'result',
#                    'solution_mode',
#                    'nondev_riskpoint_status',
#                    'task_id',
#                    'itsm_num',
#                    'memo',
                    'modified_date','modified_user',
                    ]
        else:
            static_fields = ['riskpoint','solution_id','type',
                    'policy','urgency',
                    'plan_finish_date',
#                    'finish_date',
#                    'zx_ammount','gs_ammount',
                    'lead_depart','tech_lead_depart','tech_co_depart',
                    'busi_lead_depart','busi_co_depart',
#                    'yw_ammount',
                    'solution',
#                    'result',
#                    'solution_mode','nondev_riskpoint_status','task_id',
#                    'memo',
                    'modified_date','modified_user',
                    ]


    
        if request.user.is_superuser:
            layout = [
                    '-- 风险整改措施信息 --',
                    ('riskpoint'),
                    ('solution_id','type'),
                    ('policy','urgency'),
                    ('plan_finish_date','finish_date'),
                    ('zx_ammount','gs_ammount'),
                    ('lead_depart','tech_lead_depart','tech_co_depart'),
                    ('busi_lead_depart','busi_co_depart','yw_ammount'),
                    ('solution'),
                    ('result'),
                    ('solution_additional_explan'),
                    ('solution_mode','nondev_riskpoint_status'),
                    ('task_id'),
                    ('itsm_num'),
                    ('memo'),
                    ('modified_date','modified_user'),
                    ]            
        else:
            layout = [
                    '-- 风险整改措施信息 --',
                    ('riskpoint','solution_id','type'),
                    ('policy','urgency'),
                    ('plan_finish_date','finish_date'),
                    ('zx_ammount','gs_ammount'),
                    ('lead_depart','tech_lead_depart','tech_co_depart'),
                    ('busi_lead_depart','busi_co_depart','yw_ammount'),
                    ('solution'),
                    ('result'),
                    ('solution_additional_explan'),
                    ('solution_mode','nondev_riskpoint_status'),
                    ('task_id','itsm_num'),
                    ('memo'),
                    ('modified_date','modified_user'),
                    ]
            
        def get_form_field(name, obj):
            from uliweb.utils.generic import RemoteField
#            if request.user.is_superuser:
#                if name == 'requirement':
#                    if obj._requirement_:
#                        alt = obj.requirement.title
#                    else:
#                        alt = ''
#                    return RemoteField('准开发需求', name=name, required=True, 
#                        url='/requirements/search', alt=alt)
            #当为超级用户或开发中心管理用户时，关联任务选项重置为查询控件
            if request.user.is_superuser or (request.user.department == '2' and request.user.is_gm and obj._tech_lead_depart_ == request.user._kfzx_):
                if name == 'task_id':
                    task_flag = task_dev.get(task_dev.c.id == obj._task_id_)
                    if task_flag:
                        alt = task_flag.name
                    else:
                        alt = ''
                    return RemoteField('执行任务', name=name, 
                        url='/tasks/search?flag=1', alt=alt, datatype=int,default=None)
            if request.user.is_superuser:
                if name == 'riskpoint':
                    if not request.user.is_superuser: return
                    try:
                        row = obj.riskpoint
                    except NotFound, e:
                        row = None
                    if row:
                        alt = obj.riskpoint.point_id
                    else:
                        alt = ''
                    return RemoteField('风险点', name=name, url='/riskpoint/search', alt=alt,required=True , default=None)
                
        view = EditView('risksolution', ok_url=url_for(self.__class__.list), obj=obj,
                    pre_save=pre_save, 
                    fields=fields,layout = layout,
                    static_fields = static_fields,get_form_field = get_form_field,
                    form_cls=RisksolutionForm,
#                    post_created_form=post_created_form
                    )
        
        return view.run()
    
    @expose('/risksolution/add')
    @decorators.check_role('riskpoint_manager')
    def risksolution_add(self):
        from uliweb.utils.generic import AddView
        from uliweb.orm import get_model
    #    from uliweb.form.layout import TableLayout
    #    from forms import TestForm
    #    from sqlalchemy.sql import and_, or_, not_
        from forms import RiskpointForm
        from uliweb.form.layout import TableLayout
        
        RiskpointForm.layout_class = TableLayout
        
    #    TestForm.layout_class = TableLayout
        
        def post_created_form(fcls, model):
            fcls.layout_class_args = {'label_fix':True}
        
        
        layout = [
                '-- 风险整改措施信息 --',
                ('riskpoint'),
                ('solution_id','type'),
                ('policy','urgency'),
                ('plan_finish_date'),
#                ('finish_date'),
                ('zx_ammount','gs_ammount'),
                ('lead_depart','tech_lead_depart','tech_co_depart'),
                ('busi_lead_depart','busi_co_depart','yw_ammount'),
                ('solution'),
                ('result'),
                ('solution_additional_explan'),
#                ('solution_mode','nondev_riskpoint_status'),
#                ('task_id'),
                ('itsm_num'),
                ('memo'),
#                ('modified_date','modified_user'),
                ]
        

        def get_form_field(name):
            from uliweb.utils.generic import RemoteField            
            if name == 'riskpoint':
                return RemoteField('风险点', name=name, url='/riskpoint/search',required=True , default=None)
            if name == 'task_id':
                return RemoteField('执行任务', name=name, url='/tasks/search', default=None)
        
#    
    #    if request.user.department in ('2', '3'):
        view = AddView('risksolution', url_for(self.__class__.risksolution_add), 
#                pre_save=pre_save,
                get_form_field = get_form_field,
                layout=layout, 
                form_cls=RiskpointForm, post_created_form=post_created_form,
                )
        return view.run()
    ###    else:
    #        flash('你不是开发人员和测试人员，无法添加新测试功能点！')
    #        return redirect(url_for(tests_test_list))
    
    @expose('/risksolution/delete/<int:id>')
    @decorators.check_role('riskpoint_manager')
    def risksolution_delete(self, id):
        """
        删除风险点
        """
        
        from uliweb.utils.generic import DeleteView
#        Riskpoint = get_model('riskpoint')
        obj = self.model.get(int(id))
            
        view = DeleteView('risksolution', url_for(self.__class__.list), obj=obj)
        return view.run()
